import time
import platform

# 根据平台动态导入
if platform.system() == 'Windows':
    from winpty import PtyProcess, Backend
else:
    from ptyprocess import PtyProcessUnicode as PtyProcess

from src.process.base_pro_handler import BaseProHandler


class PtyHandler(BaseProHandler):
    def __init__(self, argv):
        if platform.system() == 'Windows':
            self.__proc = PtyProcess.spawn(argv, dimensions=(24, 200), backend=Backend.WinPTY)
        else:
            self.__proc = PtyProcess.spawn([argv], dimensions=(24, 200))

    def write(self, command: str):
        self.__proc.write(command + "\r\n")

    def readline(self) -> str:
        try:
            text = self.__proc.readline()
        except EOFError:
            text = ""
        return text

    def poll(self) -> int | None:
        return self.__proc.exitstatus

    def terminate(self):
        self.__proc.terminate()

    def kill(self):
        self.__proc.terminate(force=True)

    def wait(self, wait_time: float = None) -> int | None:
        start_time = time.time()
        while self.__proc.isalive():
            time.sleep(0.1)
            if wait_time is None:
                continue
            now_time = time.time()
            if now_time - start_time > wait_time:
                raise TimeoutError
        return self.__proc.exitstatus
